// import 'babel-polyfill'
import { registerMicroApps, setDefaultMountApp, start } from 'qiankun'
import { getUrlParam } from '@/util/util'
import * as UTILS from '@/util/index'
import appsFunc from '../../../config/apps.config'
import { Vue } from '../../core'
import App from './app.vue'
import Router from './router'
import store from './store'
import { setHeaderVisible, setSideBarVisible } from './frame/methods'

Vue.config.productionTip = false

window.$frameApp = null

// const state = { userName: 'Lucy' }
// const actions = initGlobalState(state)
// actions.onGlobalStateChange((state, prev) => {
//   console.log('state', state, 'prev', prev)
// })
// actions.setGlobalState(state)
// actions.onGlobalStateChange()

// 获取用户信息
function fetchUserInfo(userInfo) {
  const instance = window.$frameApp
  instance.$store.commit(`global/${instance.$storeGlobalTypes.SET_USER_INFO}`, {
    // 是否已登录
    isLogin: true,
    // 用户信息
    info: {
      name: userInfo.realName,
      ...userInfo
    },
    // 用户中心可操作列表
    menu: []
  })
  instance.$store.commit(
    `global/${instance.$storeGlobalTypes.REGISTER_EVENT}`,
    {
      handleLogin() {
        return false
      },
      handleLogout: UTILS.logoutHandler
    }
  )
}

// 用Vue初始化微前端框架本身
function initFrame(props = {}) {
  const { userInfo } = props
  const router = Router.init(Vue)
  if (!window.$frameApp) {
    window.$frameApp = new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#frame-app')
    // fetchUserInfo()
    if (userInfo) {
      fetchUserInfo(userInfo)
    }
  }
}

// 初始化qiankun
function initQianKun(props = {}) {
  // 注册各个子应用，配置从apps.config.js中读取
  const { userInfo } = props
  const header = {
    header: false,
    userInfo,
    parentInstance: window.$frameApp
  }
  registerMicroApps(handleAppEntry(appsFunc(header), userInfo), {
    beforeLoad: [
      app => {
        console.log(app)
        console.log('[LifeCycle] before load %c%s', 'color: green;', app.name)
      }
    ],
    beforeMount: [
      app => {
        console.log('[LifeCycle] before mount %c%s', 'color: green;', app.name)
      }
    ],
    afterUnmount: [
      app => {
        console.log('[LifeCycle] after unmount %c%s', 'color: green;', app.name)
      }
    ]
  })

  // 设置默认加载的子应用路径
  setDefaultMountApp('/citycode_m/main-home')

  // 启动qiankun
  start({
    sandbox: { strictStyleIsolation: false }, // 关闭shadow dom
    // sandbox: false,
    excludeAssetFilter: url => {
      // 地图的sdk不走fetch请求
      return url.match('map.qq.com')
    }
  })
}

// 注入userInfo，并且处理本地开发调试的情况，对应的子应用entry替换为本地地址，其余的不变
function handleAppEntry(apps, userInfo) {

  let moduleEntry = getUrlParam('moduleEntry')
  let moduleName = getUrlParam('moduleName')
  if (moduleEntry && moduleName) {
    localStorage.setItem('moduleEntry', moduleEntry)
    localStorage.setItem('moduleName', moduleName)
  }
  if (
    localStorage.getItem('moduleEntry') &&
    localStorage.getItem('moduleName')
  ) {
    moduleEntry = localStorage.getItem('moduleEntry')
    moduleName = localStorage.getItem('moduleName')
  }
  apps.map(app => {
    // 以props形式注入到子应用的数据或者方法
    app.props.userInfo = userInfo
    app.props.parentInstance = window.$frameApp
    app.props.methods = {
      setHeaderVisible,
      setSideBarVisible
    }
    if (app.name === moduleName) {
      app.entry = moduleEntry
    }
  })
  return apps
}

// initFrame()
// initQianKun()

/**
 * 初始化前先确认能获取用户登录态
 */
UTILS.fetchUserInfo(null, {
  baseURL: process.env.VUE_APP_API_BASE_URL
})
  .then(res => {
    console.log('====> fetchUserInfo', res)
    initFrame({ userInfo: res })
    initQianKun({ userInfo: res })
  })
  .catch(err => {
    console.error(err)
  })


